package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.qo.EmployeeQo;
import cn.wolfcode.rbac.qo.PageQo;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.web.annotation.RequiredPermission;
import cn.wolfcode.rbac.web.vo.AdminStateVo;
import cn.wolfcode.rbac.web.vo.EmployeeRoleVo;
import cn.wolfcode.rbac.utils.R;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
//@CrossOrigin(allowCredentials = "true")
@RequestMapping("/api/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    //此时我们的admin超级管理员没有起作用，只是授予对应的权限
    //解决方案：通过自定义权限拦截方法支持超级管理
    //@PreAuthorize("@myPermission.myHasAuthority('employee:list')")
    @RequiredPermission(name="员工分页列表",expression = "employee:list")
    @PreAuthorize("hasAuthority('employee:list')")
//    @PreAuthorize("@myPermission.myHasAuthority('employee:list')")
    @GetMapping("list")
    public R list(EmployeeQo employeeQo){
        //查询员工信息
        PageInfo<Employee> pageInfo = employeeService.list(employeeQo);
        //封装员工分页的数据
        PageQo pageQo = new PageQo(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getList(), pageInfo.getTotal());
        return R.ok(pageQo);
    }

    @RequiredPermission(name="员工信息",expression = "employee:info")
    @PreAuthorize("hasAuthority('employee:info')")
    @GetMapping("info/{id}")
    public R get(@PathVariable Long id){
        Employee employee = employeeService.get(id);
        return R.ok(employee);
    }

    @RequiredPermission(name="员工保存或更新",expression = "employee:saveOrUpdate")
    @PreAuthorize("hasAuthority('employee:saveOrUpdate')")
    @PostMapping("saveOrUpdate")
    public R saveOrUpdate(@RequestBody EmployeeRoleVo employeeRoleVo){
        if(employeeRoleVo.getEmployee().getId() == null){
            employeeService.save(employeeRoleVo);
            return R.ok("员工信息保存成功");
        }else{
            employeeService.update(employeeRoleVo);
            return R.ok("员工信息更新成功");
        }
    }

    @RequiredPermission(name="员工删除",expression = "employee:delete")
    @PreAuthorize("hasAuthority('employee:delete')")
    @DeleteMapping("delete/{id}")
    public R delete(@PathVariable Long id,@RequestHeader Long userId){
        employeeService.delete(id,userId);
        return R.ok("员工信息删除成功");
    }

    /**
     * 更新员工管理员状态
     * @return
     */
    @RequiredPermission(name="员工管理员状态更新",expression = "employee:updateState")
    @PreAuthorize("hasAuthority('employee:updateState')")
    @PostMapping("updateState")
    public R updateState(@RequestBody AdminStateVo adminStateVo){
        employeeService.updateState(adminStateVo);
        return R.ok("员工管理员状态更新成功");
    }


}
